//
//  ContentViewController.m
//  Novel
//
//  Created by th on 2017/2/19.
//  Copyright © 2017年 th. All rights reserved.
//

#import "ContentViewController.h"
#import "BatteryView.h"
#import "GDTNativeExpressAd.h"
#import "GDTNativeExpressAdView.h"
#import "GDTMobBannerView.h"
#import "YFLastView.h"
#define kRandomColor ([UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0f])

@interface ContentViewController ()<GDTNativeExpressAdDelegete,GDTMobBannerViewDelegate>{
    
    UIView *_adView;            //当前展示的原生广告界面
    GDTMobBannerView *bannerView;//banner广告
    YFLastView *_lastView;//最后一页的广告
}

// 用于请求原生模板广告，注意：不要在广告打开期间释放！
@property (nonatomic, retain)   GDTNativeExpressAd *nativeExpressAd;

// 存储返回的GDTNativeExpressAdView
@property (nonatomic, retain)       NSArray *expressAdViews;

@property (nonatomic, strong) YYLabel *contentLabel;

@property (nonatomic, strong) YYLabel *titleLabel;

@property (nonatomic, strong) YYLabel *pageLabel;

@property (nonatomic, strong) BatteryView *batteryView;

@property (nonatomic, strong) YYLabel *timeLabel;

@end

@implementation ContentViewController


- (YYLabel *)contentLabel {
    if (!_contentLabel) {
        _contentLabel = [[YYLabel alloc] initWithFrame:kReadingFrame];
//        _contentLabel.backgroundColor = kLineColor;
        _contentLabel.font = FONT_SIZE(20);
        _contentLabel.numberOfLines = 0;
        _contentLabel.textAlignment = NSTextAlignmentCenter;
        [_contentLabel setTextVerticalAlignment:YYTextVerticalAlignmentTop];//居上对齐
        [self.view addSubview:_contentLabel];
    }
    return _contentLabel;
}

- (YYLabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[YYLabel alloc] initWithFrame:CGRectMake(kReadSpaceX, 0, kScreenWidth - kReadSpaceX*2, kReadSpaceY)];
        _titleLabel.font = FONT_SIZE(13);
        _titleLabel.textColor = kNormalColor;
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        [self.view addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (YYLabel *)pageLabel {
    if (!_pageLabel) {
        CGFloat w = 100;
        _pageLabel = [[YYLabel alloc] initWithFrame:CGRectMake(kScreenWidth - kReadSpaceX - w, kScreenHeight - kReadSpaceY, w, kReadSpaceY)];
        _pageLabel.font = FONT_SIZE(12);
        _pageLabel.textColor = kNormalColor;
        _pageLabel.textAlignment = NSTextAlignmentRight;
        
        [self.view addSubview:_pageLabel];
    }
    return _pageLabel;
}

- (BatteryView *)batteryView {
    if (!_batteryView) {
        _batteryView = [[BatteryView alloc] initWithFrame:CGRectMake(20, (kReadSpaceY - 10) * 0.5 + kScreenHeight - kReadSpaceY, 25, 10)];
        
        _batteryView.fillColor = [UIColor colorWithRed:0.35 green:0.31 blue:0.22 alpha:1.00];
        
         [self.view addSubview:_batteryView];
    }
    return _batteryView;
}

- (YYLabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[YYLabel alloc] initWithFrame:CGRectMake(45+kSpaceX, kScreenHeight - kReadSpaceY, 50, kReadSpaceY)];
        _timeLabel.font = FONT_SIZE(12);
        _timeLabel.textColor = kNormalColor;
        _timeLabel.textAlignment = NSTextAlignmentLeft;
        
        [self.view addSubview:_timeLabel];
    }
    return _timeLabel;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor clearColor];
    
    [self changeBgColorWithIndex:[ReadingManager shareReadingManager].bgColor];
    
    self.timeLabel.text = [[DateTools shareDate] getTimeString];
    
    [self changeOtherColor:[ReadingManager shareReadingManager].bgColor];
//
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBgColorWithNotifiction:) name:NotificationWithChangeBg object:nil];
//
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBgSelectColorWithNotifiction:) name:NotificationWithChangeBgSelect object:nil];
}

- (void)changeBgColorWithNotifiction:(NSNotification *)sender {
    
    NSUInteger index = [[sender userInfo][NotificationWithChangeBg] integerValue];
    
    [self changeBgColorWithIndex:index];
}
- (void)changeBgSelectColorWithNotifiction:(NSNotification *)sender {
    
    NSUInteger index = [[sender userInfo][NotificationWithChangeBgSelect] integerValue];
    
    [self changeBgColorWithIndex:index];
}


/** 0-白色 1-黄色 2-淡绿色 3-淡黄色 4-淡紫色 */
- (void)changeBgColorWithIndex:(NSUInteger)index {
    
    NSArray *imgs = @[@"day_mode_bg", @"yellow_mode_bg", @"green_mode_bg", @"sheepskin_mode_bg", @"pink_mode_bg", @"coffee_mode_bg"];
    
    UIImage *bgImage = [UIImage imageNamed:imgs[index]];
    self.view.layer.contents = (__bridge id _Nullable)(bgImage.CGImage);
    
    [self changeOtherColor:index];
    
    self.batteryView.backgroundColor = [bgImage mostColor];
    
    [self.batteryView setNeedsDisplay];
}

- (void)changeOtherColor:(NSUInteger)index {
    if ([ReadingManager shareReadingManager].bgColor == 5) {
        
        NSMutableAttributedString *text = (NSMutableAttributedString *)self.contentLabel.attributedText;
        text.color = KWhiteColor;
        
        self.contentLabel.attributedText = text;
        
        self.titleLabel.textColor = KWhiteColor;
        self.timeLabel.textColor = KWhiteColor;
        self.pageLabel.textColor = KWhiteColor;
        
    } else {
        
        NSMutableAttributedString *text = (NSMutableAttributedString *)self.contentLabel.attributedText;
        text.color = kBlackColor;
        
        self.contentLabel.attributedText = text;
        
        self.titleLabel.textColor = kNormalColor;
        self.timeLabel.textColor = kNormalColor;
        self.pageLabel.textColor = kNormalColor;
    }
}


- (void)setBookModel:(BookChapterModel *)bookModel {
    
    _bookModel = bookModel;
    
    self.titleLabel.text = bookModel.title;
}
    
- (void)setPage:(NSUInteger)page {
    
    _page = page;
    
    self.contentLabel.attributedText = [_bookModel getStringWithpage:page];
    
    self.pageLabel.text = [NSString stringWithFormat:@"%zd/%zd",page+1,_bookModel.pageCount];
    //添加广告
    if (page +2 == _bookModel.pageCount) {
        //计算出内容显示的位置
        CGSize size = [self.contentLabel.attributedText boundingRectWithSize:CGSizeMake(kScreenWidth - kReadSpaceX*2, kScreenHeight - kReadSpaceY*2) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
        CGFloat h = kScreenHeight - kReadSpaceY*2 - size.height;
        CGFloat w = kScreenWidth - kReadSpaceX*2;
        CGFloat h2 = 720 * w * 1.0 / 1280;
        CGFloat h3 = GDTMOB_AD_SUGGEST_SIZE_320x50.height *( kScreenWidth - kReadSpaceX*2) / GDTMOB_AD_SUGGEST_SIZE_320x50.width;
        
        if (h >= h2) {
            //h = h2;
            //加载广告
            [self loadGDT:CGSizeMake(w, h2)];
            //判断最后一页的字符
            _adView.frame = CGRectMake(kReadSpaceX, kReadSpaceY + size.height, kScreenWidth - kReadSpaceX*2, h2);
            
        }else if(h >= h3){
            
            bannerView = [[GDTMobBannerView alloc] initWithFrame:CGRectMake(kReadSpaceX,kReadSpaceY + size.height,kScreenWidth - kReadSpaceX*2,GDTMOB_AD_SUGGEST_SIZE_320x50.height *( kScreenWidth - kReadSpaceX*2) / GDTMOB_AD_SUGGEST_SIZE_320x50.width)
                                                          appkey:@"1106505410" placementId:@"5090021722761648"];
            self.extendedLayoutIncludesOpaqueBars = NO;
            self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
            bannerView.delegate = self;
            bannerView.currentViewController = self;
            bannerView.isAnimationOn = NO;
            bannerView.showCloseBtn = YES;
            bannerView.interval = 10;
            bannerView.isGpsOn = NO;
            [bannerView loadAdAndShow];
            [self.view addSubview:bannerView];
        }
        
    }else if (page +1 == _bookModel.pageCount){
        
        //最后一页大图
        _lastView = [[YFLastView alloc]initWithFrame:CGRectMake(kReadSpaceX, kReadSpaceY, kScreenWidth - 2 * kReadSpaceX, kScreenHeight - 2 * kReadSpaceY)];
        _lastView.rootVC = self;
        [self.view addSubview:_lastView];
    }else{
        
        _adView.frame = CGRectZero;
        _lastView.frame = CGRectZero;
    }
}

- (void)loadGDT:(CGSize)size
{
    
    self.nativeExpressAd = [[GDTNativeExpressAd alloc] initWithAppkey:@"1106505410" placementId:@"1090826792761504" adSize:size];
    self.nativeExpressAd.delegate = self;
    
    // 拉取5条广告
    [self.nativeExpressAd loadAd:3];
    
    _adView = [[UIView alloc]initWithFrame:CGRectZero];
    _adView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_adView];
}

//- (void)loadBanner{
//
//
//}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ----bannner
// 请求广告条数据成功后调用
//
// 详解:当接收服务器返回的广告数据成功后调用该函数
- (void)bannerViewDidReceived
{
    NSLog(@"banner Received");
}

// 请求广告条数据失败后调用
//
// 详解:当接收服务器返回的广告数据失败后调用该函数
- (void)bannerViewFailToReceived:(NSError *)error
{
    NSLog(@"banner failed to Received : %@",error);
}

#pragma mark -----广告数据代理

/**
 * 拉取广告成功的回调
 */
- (void)nativeExpressAdSuccessToLoad:(GDTNativeExpressAd *)nativeExpressAd views:(NSArray<__kindof GDTNativeExpressAdView *> *)views
{
    [self.expressAdViews enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GDTNativeExpressAdView *adView = (GDTNativeExpressAdView *)obj;
        [adView removeFromSuperview];
    }];
    
    self.expressAdViews = [NSArray arrayWithArray:views];
    
    if (self.expressAdViews.count) {
        
        // 取一个GDTNativeExpressAdView
        GDTNativeExpressAdView *expressView =  [self.expressAdViews objectAtIndex:0];
        // 设置frame，开发者自己设置
        expressView.frame = CGRectMake(0, 0, CGRectGetWidth(_adView.frame), CGRectGetHeight(_adView.frame));
        expressView.controller = self;
        [expressView render];
        //添加View的时机，开发者控制
        [_adView addSubview:expressView];
        
        
    }
    
}

/**
 * 拉取广告失败的回调
 */
- (void)nativeExpressAdFailToLoad:(GDTNativeExpressAd *)nativeExpressAd error:(NSError *)error {
    
}
/**
 * 拉取广告失败的回调
 */
- (void)nativeExpressAdRenderFail:(GDTNativeExpressAdView *)nativeExpressAdView
{
    NSLog(@"%s",__FUNCTION__);
}

- (void)nativeExpressAdViewRenderSuccess:(GDTNativeExpressAdView *)nativeExpressAdView
{
    NSLog(@"%s",__FUNCTION__);
}

- (void)nativeExpressAdViewClicked:(GDTNativeExpressAdView *)nativeExpressAdView
{
    NSLog(@"%s",__FUNCTION__);
}
@end

